<template>
    <el-dialog
        v-model="addOrderUseSystemVisible"
        draggable
        :show-close="false"
        :close-on-click-modal="false"
        width="80%"
        @open="addOrderUseSystemOpen"
    >
        <!-- 自定义头部 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">录入订单</h4>
                <el-button type="danger" :icon="CircleCloseFilled" @click="close"> 关闭 </el-button>
            </div>
        </template>
        <!-- 内容 -->
        <div class="grid grid-cols-1 gap-2">
            <!-- 订单抬头信息 -->
            <div class="grid grid-cols-4 gap-1 justify-center items-center">
                <!-- 订单日期 -->
                <div>
                    <el-text>订单日期：</el-text>
                    <el-date-picker v-model="addOrderUseSystemForm.orderDate" type="datetime" placeholder="请输入订单日期" disabled />
                </div>
                <!-- 送货日期 -->
                <div class="col-span-2">
                    <el-radio-group v-model="customerDeliveryDate" class="!flex-nowrap">
                        <!-- 送货日期 -->
                        <el-radio :value="false">
                            <el-text>送货日期：</el-text>
                            <el-date-picker
                                v-model="addOrderUseSystemForm.orderDeliveryDate"
                                type="date"
                                placeholder="请输入到货日期"
                                clearable
                            ></el-date-picker>
                        </el-radio>
                        <!-- 暂无送货计划 -->
                        <el-radio :value="true">暂无送货计划</el-radio>
                    </el-radio-group>
                </div>
                <!-- 订单号 -->
                <div class="flex">
                    <el-input v-model="addOrderUseSystemForm.orderNo" clearable>
                        <template #prepend>订单号：</template>
                    </el-input>
                    <el-button class="ml-2" type="primary" @click="creatRandomOrderNo">随机生成</el-button>
                </div>
            </div>
            <!-- 订单备注 -->
            <div class="grid grid-cols-1 gap-1">
                <!-- 订单备注 -->
                <el-input v-model="addOrderUseSystemForm.orderRemark" :rows="2" type="textarea" placeholder="请输入订单备注"></el-input>
            </div>
            <!-- 订单内容选项 -->
            <div class="flex justify-between">
                <div>
                    <el-button plain :icon="Plus" @click="addRow">添加</el-button>
                    <el-button class="mr-2" plain :icon="Delete" @click="deleteRow">删除</el-button>
                    <el-switch v-model="includTaxPriceSymbol" inline-prompt active-text="含税" inactive-text="不含税" @change="switchPrice" />
                </div>
                <div>
                    <!-- 订单总价 -->
                    <el-text type="success" tag="b" size="large">订单总价:{{ addOrderUseSystemForm.orderAmount }}</el-text>
                    <!-- 确认录入 -->
                    <el-button class="ml-10" type="primary" :icon="Select" @click="enterForm">确定录入</el-button>
                </div>
            </div>
            <!-- 订单内容信息 -->
            <div v-for="(item, index) in addOrderUseSystemForm.orderDetail" :key="index" class="grid grid-cols-7 gap-1">
                <!-- 物料号 -->
                <el-input v-model="item.materialNumber" placeholder="请输入物料号" clearable></el-input>
                <!-- 产品名称 -->
                <el-autocomplete
                    v-model="item.productName"
                    placeholder="请输入产品名称"
                    clearable
                    :fetch-suggestions="querySearch"
                    @select="handleSelect(item)"
                />
                <!-- 尺寸 -->
                <el-input v-model="item.productSize" placeholder="请输入尺寸" clearable></el-input>
                <!-- 数量 -->
                <el-input v-model="item.orderNumber" type="number" @change="calculateSubtotal(item)">
                    <template #prepend>数量</template>
                </el-input>
                <!-- 不含税 -->
                <el-input v-if="!includTaxPriceSymbol" v-model="item.excludTaxPrice" type="number" @change="calculateSubtotal(item)">
                    <template #prepend>不含税</template>
                </el-input>
                <!-- 含税价 -->
                <el-input v-if="includTaxPriceSymbol" v-model="item.includeTaxPrice" type="number" @change="calculateSubtotal(item)">
                    <template #prepend>含税</template>
                </el-input>
                <!-- 小计 -->
                <el-input v-model="item.subtotal" type="number" disabled>
                    <template #prepend>小计</template>
                </el-input>
                <!-- 备注 -->
                <el-input v-model="item.remark" placeholder="请输入备注" clearable></el-input>
            </div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { CircleCloseFilled, Plus, Delete, Select } from '@element-plus/icons-vue';
import { creatRandomNo, KeepTwoDecimalPlaces } from '@utils/calculate';
import { getProductList } from '@api/product';
import { createOrder } from '@api/order';
import { useUserStore } from '@/store/modules/user';

onMounted(() => {});

/* ******************************通用属性/方法****************************** */
// 组件实例
const instance = getCurrentInstance();
// 客户信息类型
type CustomerInfo = {
    customerId: string;
    customerName: string;
    customerAbbreviation: string;
};
const props = defineProps({
    customerInfo: { type: Object as PropType<CustomerInfo>, required: true },
});
// 添加订单弹窗显示状态
const addOrderUseSystemVisible = defineModel<boolean>({ required: true });
// 客户产品库
const productList = reactive<AjaxResponse['productList']>([]);

/* ******************************选项操作属性/方法****************************** */
// 含税标识
const includTaxPriceSymbol = ref(true);
// 含税/不含税切换标识
const switchPrice = () => {
    // 改变标识
    addOrderUseSystemForm.orderTax = includTaxPriceSymbol.value;
    // 重新计算所有小计
    for (let index = 0; index < addOrderUseSystemForm.orderDetail.length; index++) {
        const item = addOrderUseSystemForm.orderDetail[index];
        includTaxPriceSymbol.value
            ? (item.subtotal = KeepTwoDecimalPlaces(item.includeTaxPrice * item.orderNumber))
            : (item.subtotal = KeepTwoDecimalPlaces(item.excludTaxPrice * item.orderNumber));
    }
    // 重新计算总价
    addOrderUseSystemForm.orderAmount = KeepTwoDecimalPlaces(addOrderUseSystemForm.orderDetail.reduce((pre, cur) => pre + cur.subtotal, 0));
};
// 添加订单表单的行数据
const addRow = () => {
    addOrderUseSystemForm.orderDetail.push({
        productId: '',
        materialNumber: '',
        productName: '',
        productSize: '',
        includeTaxPrice: 0,
        excludTaxPrice: 0,
        orderNumber: 0,
        subtotal: 0,
        remark: '',
    });
};
// 删除订单表单的行数据
const deleteRow = () => addOrderUseSystemForm.orderDetail.pop();

// 确定录入
const enterForm = () => {
    // 如果新产品价格未确定，则影响录入，这几行代码删除可以后续录入价格
    // if (addOrderUseSystemForm.orderAmount == 0) {
    //     ElMessage({
    //         message: '请先录入产品后再重试',
    //         grouping: true,
    //     });
    //     return;
    // }

    if (!addOrderUseSystemForm.orderDate || !addOrderUseSystemForm.orderDeliveryDate) {
        ElMessage({
            message: '请先选择日期',
            grouping: true,
        });
        return;
    }

    if (addOrderUseSystemForm.orderNo == '') {
        ElMessage({
            message: '请先输入订单号',
            grouping: true,
        });
        return;
    }

    if (addOrderUseSystemForm.customerId == '') {
        ElMessage({
            message: '请先选择客户',
            grouping: true,
        });
        return;
    }

    // 最后加工一次数据
    addOrderUseSystemForm.orderDeliveryDate = customerDeliveryDate.value ? '暂无送货计划' : addOrderUseSystemForm.orderDeliveryDate;

    createOrder(addOrderUseSystemForm).then(() => {
        ElMessage({
            message: '添加订单成功',
            type: 'success',
            grouping: true,
        });
        addOrderUseSystemVisible.value = false;
        // 发送添加订单完成更新订单列表事件
        instance?.proxy?.$Bus.emit('updateOrderList');
    });
};

/* ******************************添加订单属性/方法****************************** */
// 送货时间可选项
const customerDeliveryDate = ref(true);
// 添加订单表单
const addOrderUseSystemForm = reactive<AjaxRequest['addOrderUseSystemForm']>({
    customerId: '',
    customerName: '',
    orderDate: new Date(),
    orderNo: '',
    orderDeliveryDate: new Date(),
    orderRemark: '',
    orderTax: includTaxPriceSymbol.value,
    orderAmount: 0,
    orderDetail: [
        {
            productId: '',
            materialNumber: '',
            productName: '',
            productSize: '',
            orderNumber: 0,
            excludTaxPrice: 0,
            includeTaxPrice: 0,
            subtotal: 0,
            remark: '',
        },
    ],
    creatorId: useUserStore().id,
    creator: useUserStore().username,
});
// 添加订单弹窗打开事件 -- 加载对应客户产品库
const addOrderUseSystemOpen = () => {
    // 加载对应客户id
    addOrderUseSystemForm.customerId = props.customerInfo.customerId;
    addOrderUseSystemForm.customerName = props.customerInfo.customerName;
    // 加载对应下单时间
    addOrderUseSystemForm.orderDate = new Date();
    // 加载对应产品库
    getProductList(props.customerInfo.customerId).then((res) => {
        if (res.data.length == 0) {
            ElMessage({
                message: '暂无当前客户产品，请先添加产品后重试',
                type: 'warning',
                grouping: true,
            });
            addOrderUseSystemVisible.value = false;
        }
        // 清空上次数据
        productList.splice(0);
        // 处理成自动填充框数据格式
        res.data.forEach((item: any) => {
            item.value = item.productName;
            productList.push(item);
        });
    });
};
// 生成随机订单号
const creatRandomOrderNo = () => {
    addOrderUseSystemForm.orderNo = new creatRandomNo().id;
};

/* ******************************自动填充框属性/方法****************************** */
// 查询搜索
const querySearch = (queryString: string, cb: any) => {
    const results = queryString ? productList.filter(createFilter(queryString)) : productList;
    cb(results);
};
const createFilter = (queryString: string) => {
    return (product: any) => {
        // 匹配产品名称
        return new RegExp(queryString.toLowerCase()).test(product.productName.toLowerCase());
    };
};
// 产品选中事件
const handleSelect = (item: (typeof addOrderUseSystemForm)['orderDetail'][0]) => {
    // 获取对应产品信息
    productList.forEach((product) => {
        if (product.productName == item.productName) {
            item.productId = product._id;
            item.materialNumber = product.materialNumber;
            item.productSize = product.productSize;
            item.excludTaxPrice = product.excludTaxPrice;
            item.includeTaxPrice = product.includeTaxPrice;
        }
    });
    // 重新计算金额
    calculateSubtotal(item);
};
// 计算小计-总计
const calculateSubtotal = (item: (typeof addOrderUseSystemForm)['orderDetail'][0]) => {
    // 重新计算小计
    if (includTaxPriceSymbol) {
        item.subtotal = KeepTwoDecimalPlaces(item.includeTaxPrice * item.orderNumber);
    } else {
        item.subtotal = KeepTwoDecimalPlaces(item.excludTaxPrice * item.orderNumber);
    }
    // 重新计算总计
    addOrderUseSystemForm.orderAmount = KeepTwoDecimalPlaces(addOrderUseSystemForm.orderDetail.reduce((acc, curr) => acc + curr.subtotal, 0));
};
</script>

<style scoped>
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
</style>
